package com.haredot.entity;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.github.hiwepy.qqwry.spring.boot.ext.QQWry;
import com.haredot.constraint.RabbitConst;
import com.haredot.typehandler.IPTypeHandler;
import com.haredot.utils.ClientIPUtil;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_login_log")
public class SignInLog {

    @TableId(value = "id", type = IdType.ASSIGN_ID)
    @JsonSerialize(using = ToStringSerializer.class)
    private Long id ;

    @TableField("os_name")
    private String osName ;

    @TableField("browser_name")
    private String browserName ;

    @TableField(value = "ip", typeHandler = IPTypeHandler.class)
    private String ip ;

    private String address ;

    private boolean state ;

    private String reason ;

    private String user ;

    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private LocalDateTime createTime ;


    public static void sendLog(HttpServletRequest request, QQWry qqWry,  RabbitTemplate rabbitTemplate, String user , boolean state, String reason) {
        String clientIP = ClientIPUtil.getClientIP(request);

        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        // 记录成功日志
        SignInLog log = SignInLog.builder()
                .ip(clientIP)
                .address(qqWry.findIP(clientIP).getMainInfo())
                .osName(userAgent.getOperatingSystem().getName())
                .browserName(userAgent.getBrowser().getName())
                .state(state)
                .user(user)
                .reason(reason)
                .createTime(LocalDateTime.now())
                .build();

        String jsonString = JSONArray.toJSONString(log);

        rabbitTemplate.send(RabbitConst.SIGN_LOGS_QUEUE,  new Message(jsonString.getBytes(StandardCharsets.UTF_8)));
    }

}
